import { usePagination } from '@/hooks';
import { computed, onMounted, reactive, Ref, ref } from 'vue';
import { createUser, getUsers, login, updateUser } from '@/api/user';
import { Log, QueryParams } from '@/types';
import { getUserlogs } from '@/api/log';
import { User } from '@/types';
import { useForm } from '@ant-design-vue/use';
import { message } from 'ant-design-vue';

const columns = [
  {
    title: '用户名',
    dataIndex: 'username',
    width: 120,
  },
  {
    title: '姓名',
    width: 120,
    dataIndex: 'name',
  },
  {
    title: '邮箱',
    width: 200,
    dataIndex: 'email',
  },
  {
    title: '角色',
    dataIndex: 'roles',
    slots: { customRender: 'roles' },
  },
  {
    title: '状态',
    dataIndex: 'status',
    width: 60,
    slots: { customRender: 'status' },
  },
  {
    title: '创建时间',
    dataIndex: 'created_at',
    width: 160,
    slots: { customRender: 'createdAt' },
  },
  {
    title: '操作',
    width: 160,
    slots: { customRender: 'operation' },
  },
];

export const useUser = () => {
  const data = ref([]);
  const current = ref(1);
  const pageSize = ref(10);
  const total = ref(30);
  const loading = ref(false);

  const search = async (params: QueryParams) => {
    loading.value = true;
    const response = await getUsers(params);

    if (response != undefined && response.status == 200) {
      data.value = response.data.items;
      current.value = params.page;
      pageSize.value = params.pageSize;
      total.value = response.data.total;
    }
    loading.value = false;
  };

  const pagination = computed(() => ({
    total: total.value,
    current: current.value,
    pageSize: pageSize.value,
  }));

  onMounted(() => {
    search({
      pageSize: pageSize.value,
      page: current.value,
    });
  });

  return {
    data,
    search,
    pagination,
    columns,
    loading,
  };
};

const postUser = async (form: any) => {
  if (form.id == '' || form.id == undefined) {
    return await createUser(form);
  }
  return await updateUser(form);
};

export const usePostUser = () => {
  const submitting = ref(false);
  const loginForm = reactive({
    id: '',
    username: '',
    name: '',
    email: '',
    roles: [],
    status: 10,
  });

  const rulesRef = reactive({
    username: [{ required: true, message: '请输入用户名', whitespace: true }],
    name: [{ required: true, message: '姓名不能为空', whitespace: true }],
    email: [
      { required: false, message: '邮箱格式不正确', pattern: '^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(.[a-zA-Z0-9_-]+)+$' },
    ],
    status: [{ required: true, type: 'enum', enum: [9, 10], message: 'status不正确' }],
  });
  const { validate, validateInfos, resetFields } = useForm(loginForm, rulesRef);

  const post = async () => {
    try {
      await validate();
    } catch (e) {
      console.error(e);
      return;
    }
    submitting.value = true;
    try {
      const res = await postUser(loginForm);
      if (res != undefined && res.status == 200) {
        message.info(res.message);
      } else {
        message.warn(res != undefined ? res.message : '操作失败！');
      }
    } catch (e) {
      console.log(e);
    } finally {
      submitting.value = false;
    }
  };

  return {
    form: loginForm,
    post,
    submitting,
    resetForm: resetFields,
    errors: validateInfos,
  };
};

export const useUserLog = () => {
  const logs: Ref<Log[]> = ref([]);

  const request = async (id: number) => {
    const res = await getUserlogs(id);
    if (res != undefined && res.status == 200) {
      logs.value = res.data;
    }
  };

  return {
    request,
    data: logs,
  };
};
